﻿using UnityEngine;
using System.Collections;
using WyrmTale;
#if UNITY_EDITOR
using UnityEditor;
#endif

[System.Serializable]
public class StatData
{
	public float minValue;
	public float maxValue;
	public StatBonus bonus;

	public StatData()
	{
		minValue = 0f;
		maxValue = 0f;
		bonus = null;
	}

	public int GetAverageValue(bool _roundUp = true)
	{
		float value = 0f;
		if (maxValue == 0f)
		{
			value = minValue;
		}
		else
		{
			value = (maxValue + minValue) / 2f;
		}

		if (_roundUp)
		{
			return Mathf.CeilToInt(value);
		}
		else
		{
			return Mathf.FloorToInt(value);
		}
	}

	public float GetRandomValue()
	{
		if (maxValue == 0f)
		{
			return minValue;
		}
		else
		{
			return Random.Range(minValue, maxValue);
		}
	}

	public float GetValue()
	{
		return minValue;
	}
	
	public int GetPercentage()
	{
		return Mathf.RoundToInt(minValue / maxValue * 100f);
	}
	
	public string GetDisplayString()
	{
		return GetPercentage() + "%";
	}

	public static StatData operator +(StatData _data, StatBonus _bonus) 
	{
		StatData data = _data.Clone();
		data.minValue += _bonus.minValue;
		data.maxValue += _bonus.maxValue;
		return data;
	}
	
	#region Editor
	public void Draw(string _name, bool _doubleValue, string _divider = "")
	{
		EditorGUILayout.BeginHorizontal();
		{
			if (_doubleValue)
			{
				EditorGUILayout.LabelField(_name, GUILayout.Width(75));
				minValue = EditorGUILayout.FloatField(minValue);
				EditorGUILayout.LabelField(_divider, GUILayout.Width(10));
				maxValue = EditorGUILayout.FloatField(maxValue);
			}
			else
			{
				EditorGUILayout.LabelField(_name, GUILayout.Width(70));
				minValue = EditorGUILayout.FloatField(minValue);
			}
		}
		EditorGUILayout.EndHorizontal();
	}
	#endregion
	
	public StatData Clone()
	{
		StatData data = new StatData();
		data.minValue = minValue;
		data.maxValue = maxValue;
		data.bonus = bonus != null ? bonus.Clone() : null;
		return data;
	}
}

#if UNITY_EDITOR
[CustomPropertyDrawer(typeof(StatData))]
public class StatDrawer : PropertyDrawer
{
	public override void OnGUI (Rect position, SerializedProperty property, GUIContent label)
	{
		EditorGUI.BeginProperty(position, label, property);
		
		float indentLength = 15f * EditorGUI.indentLevel;
		Rect rect = new Rect(position);
		position.width -= 80f * 1f + 60f * 2f;
		position.width += 10f * 1f + 20f * 2f + indentLength * 1f;
		
		rect.width = 80f;
		EditorGUI.PrefixLabel(rect, label);
		
		rect.x += rect.width - 10f;
		rect.width = 60f;
		EditorGUI.LabelField(rect, "v1");
		
		rect.x += rect.width - 20f;
		rect.width = position.width * 0.5f;
		EditorGUI.PropertyField(rect, property.FindPropertyRelative("minValue"), GUIContent.none, true);
		
		rect.x += rect.width - indentLength;
		rect.width = 60f;
		EditorGUI.LabelField(rect, "v2");
		
		rect.x += rect.width - 20f;
		rect.width = position.width * 0.5f;
		EditorGUI.PropertyField(rect, property.FindPropertyRelative("maxValue"), GUIContent.none, true);
		
		EditorGUI.EndProperty();
	}
}
#endif
